import request from '../../../../utils/request'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,           // 订单ID
    orderDetail: null,       // 订单详情
    loading: true,           // 加载状态
    remainingTime: '15:00',  // 支付剩余时间
    timer: null,             // 倒计时定时器
    showButtons: true        // 是否显示底部按钮
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 接收订单ID参数
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      });
      console.log('接收到订单ID：', options.orderId);
      
      // 加载订单详情
      this.loadOrderDetail();
    } else {
      wx.showToast({
        title: '订单ID不存在',
        icon: 'none'
      });
    }
  },

  /**
   * 加载订单详情
   */
  loadOrderDetail() {
    const that = this;
    const { orderId } = this.data;

    wx.showLoading({
      title: '加载中...',
    });

    request({
      url: `/le/management/orderDetail?orderId=${orderId}`,
      method: 'GET',
      success: (res) => {
        console.log('订单详情返回：', res);
        wx.hideLoading();
        
        if (res.statusCode === 200 && res.data.code === 200) {
          const orderDetail = res.data.data;
          
          that.setData({
            orderDetail: orderDetail,
            loading: false
          });

          // 如果是待支付状态，根据订单创建时间计算剩余时间并启动倒计时
          if (orderDetail.orderStatus === '1' && orderDetail.createTime) {
            that.startCountdownFromCreateTime(orderDetail.createTime);
          }
        } else {
          that.setData({ loading: false });
          wx.showToast({
            title: res.data.msg || '加载订单失败',
            icon: 'none'
          });
          
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      },
      fail: (err) => {
        console.error('加载订单失败：', err);
        wx.hideLoading();
        that.setData({ loading: false });
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },

  /**
   * 启动倒计时
   */
  startCountdown(seconds) {
    const that = this;
    let remaining = seconds;

    const updateTime = () => {
      const minutes = Math.floor(remaining / 60);
      const secs = remaining % 60;
      const timeStr = `${String(minutes).padStart(2, '0')}分${String(secs).padStart(2, '0')}秒`;
      
      that.setData({
        remainingTime: timeStr
      });

      if (remaining <= 0) {
        clearInterval(that.data.timer);
        wx.showToast({
          title: '支付超时，订单已取消',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }

      remaining--;
    };

    updateTime();
    const timer = setInterval(updateTime, 1000);
    this.setData({ timer });
  },

  /**
   * 格式化日期时间
   */
  formatDateTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}.${month}.${day} ${hour}:${minute}:${second}`;
  },

  /**
   * 取消订单
   */
  quxiao() {
    const { orderId } = this.data;
    // 跳转到原因选择页面
    wx.navigateTo({
      url: `/pages/my/yuanyin/yuanyin?orderId=${orderId}`
    });
  },

  /**
   * 去支付
   */
  goPay() {
    const { orderId } = this.data;
    // 跳转到支付页面
    wx.navigateTo({
      url: `/pages/serve/servePay/servePay?orderId=${orderId}`
    });
  },

  /**
   * 申请退款
   */
  refund() {
    const { orderId } = this.data;
    // 跳转到原因选择页面
    wx.navigateTo({
      url: `/pages/my/yuanyin/yuanyin?orderId=${orderId}&type=refund`
    });
  },

  /**
   * 联系客服
   */
  contactService() {
    wx.showToast({
      title: '客服功能开发中',
      icon: 'none'
    });
  },

  /**
   * 根据订单创建时间启动倒计时
   * 确保同一订单在不同页面、不同时间打开都显示正确的剩余时间
   */
  startCountdownFromCreateTime(createTime) {
    const that = this;
    
    // 解析订单创建时间
    const createDate = new Date(createTime.replace(/-/g, '/'));
    const now = new Date();
    
    // 计算已经过去的秒数
    const elapsedSeconds = Math.floor((now - createDate) / 1000);
    
    // 10分钟 = 600秒
    const totalSeconds = 10 * 60;
    
    // 计算剩余秒数
    let remainingSeconds = totalSeconds - elapsedSeconds;
    
    if (remainingSeconds <= 0) {
      // 已超时，订单应该已被后台自动关闭
      that.setData({
        remainingTime: '已超时'
      });
      return;
    }
    
    // 启动倒计时
    this.startCountdown(remainingSeconds);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除倒计时
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  }
})